//
//  OAuthViewController.m
//  我的微博
//
//  Created by tom-1 on 15/12/8.
//  Copyright © 2015年 tom-1. All rights reserved.
//

#import "OAuthViewController.h"
#import "NetworkTools.h"
#import "UserAccout.h"

@interface OAuthViewController () <UIWebViewDelegate>
@property (nonatomic,strong) UIWebView *webView;
@end

@implementation OAuthViewController
#pragma mark - 懒加载
- (UIWebView *)webView {
    if (_webView == nil) {
        self.webView = [[UIWebView alloc] init];
    }
    return _webView;
}
#pragma mark - 监听方法
- (void)close {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)autoFill {

    NSString *tou = @"document.getElementById('userId').value = 'daoge10000@sina.cn';";
    NSString *wei = @"document.getElementById('passwd').value = 'qqq123';";
    NSString *js = [NSString stringWithFormat:@"%@%@",tou,wei];
    // 让webView执行js
    [self.webView stringByEvaluatingJavaScriptFromString:js];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NetworkTools *workTools = [NetworkTools sharedTools];
    
    // 加载页面
    [self.webView loadRequest:[NSURLRequest requestWithURL:workTools.oauthURL]];
    NSLog(@"%@",workTools.oauthURL);
}

- (void)loadView {
    self.view = self.webView;
    // 设置代理
    self.webView.delegate = self;
    // 设置导航栏
    self.title = @"登录新浪微博";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"自动填充" style:UIBarButtonItemStylePlain target:self action:@selector(autoFill)];
}

#pragma mark - 代理方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    // 如果是百度就不要去加载
    NSURL *url = request.URL;
//    NSLog(@"url = %@",url);
    if (![url.host  isEqualToString: @"www.baidu.com"]) {
//        NSLog(@"url.host = %@",url.host);
        return YES;
    }
    // 从百度地址的url 中提取 `code=` 是否存在
    NSString *query = url.query;
//    NSLog(@"query = %@",query);
    if (![query hasPrefix:@"code="]) {
        NSLog(@"取消授权");
        return YES;
    }
    // 从query字符串中取得code后面的授权码

    NSString *code = [query substringFromIndex:5];
    
    NSLog(@"授权码是 %@",code);
    // 加载accessToken
    [[NetworkTools sharedTools] loadAccessToken:code finished:^(id result, NSError *error) {
        // 1.判断是否出错
        if (error != nil) {
            NSLog(@"出错了");
            return;
        }
        // 2.输出结果
        NSLog(@"%@",result);
       
        UserAccout *accout = [[UserAccout alloc] initWithDict:result
                              ];
        [self loadUserInfo: accout];
    }];
    
    return NO;
}

- (void)loadUserInfo: (UserAccout *)accout {
    [[NetworkTools sharedTools] loadUserInfo:accout.uid accessToken:accout.access_token finished:^(id result, NSError *error) {
        if (error != nil) {
            NSLog(@"加载用户数据出错");
            return;
        }
        NSDictionary *dict = [NSDictionary dictionary];
        if (dict == nil) {
            NSLog(@"格式错误");
            return;
        }
        //dict一定给hi一个有值的字典
        //将用户信息保存
        accout.screen_name = dict[@"screen_name"];
        accout.avatar_large = dict[@"avatar_large"];
        NSLog(@"%@",accout);
        [accout saveUserAccount];
    }];
}

@end
